import React from "react";

// 引入路由的组件
import { BrowserRouter, useRoutes } from 'react-router-dom';

// 获取所有的页面路由
import routes from '~react-pages';

// 引入路由规则
import rules from "@/routers/rules";

export default function App()
{
    const Routers = () =>
    {
        // 把跳转页面的API挂载全局
        React.navigate = useNavigate();

        const { pathname } = useLocation();

        useEffect(() =>
        {
            if(!rules.includes(pathname))
            {
                check();
            }
        },[pathname]);

        const check = async () =>
        {
            // 从cookie里获取用户信息
            const business = React.Cookies.load('business') ? React.Cookies.load('business') : {};

            // 如果等于0就说明当前是处于没有登录
            if(Object.getOwnPropertyNames(business).length === 0)
            {
                React.success('请先登录',() => React.navigate('/business/login'));

                return false;
            }

            // 获取用户id以及手机号
            const id = business.id ?? 0;
            const mobile = business.mobile ?? '';

            // 组装请求参数
            const params = {
                id,
                mobile
            }

            // 发起请求验证数据是否真实有效
            const result = await React.http.post('/business/check',params);

            if(result.code === 1)
            {
                // 重新更新cookie值以及全局属性的值
                React.Cookies.save('business',result.data,{path:'/'});
                
                React.business = result.data;
            }else{
                React.fail(result.msg,() =>
                {
                    React.Cookies.remove('business',{path:'/'});

                    React.navigate(result.url);
                });

                return false;
            }
        }

        return (
            <React.Suspense fallback={<React.UI.AutoCenter><React.UI.DotLoading color='primary' /></React.UI.AutoCenter>}>
                {useRoutes(routes)}
            </React.Suspense>
        )
    }

    return (
        <BrowserRouter>
            <Routers />
        </BrowserRouter>
    )
}